package com.ztewatch.wearcontacts.calllog;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.database.Cursor;
import android.os.Environment;
import android.os.Handler;
import android.provider.CallLog.Calls;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.common.widget.GroupingListAdapter;
import com.ztewatch.wearcontacts.R;
import com.ztewatch.wearcontacts.view.CustomProgressBar;

public class CallLogAdapter extends GroupingListAdapter implements
		CallLogGroupBuilder.GroupCreator, Recorder.OnStateChangedListener {
	private static final int MAX_CALL_TYPE_ICONS = 3;
	CallLogGroupBuilder mCallLogGroupBuilder;
	LayoutInflater mInflater;
	Activity mContext;
	private Recorder player;

	public CallLogAdapter(Activity context) {
		super(context);
		mContext = context;
		mInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mCallLogGroupBuilder = new CallLogGroupBuilder(this);
		player = new Recorder(context);
		player.setOnStateChangedListener(this);
	}

	public void bindView(View view, Cursor c, final int count) {
		final String number = c.getString(CallLogQuery.NUMBER);
		final String name = c.getString(CallLogQuery.CACHED_NAME);
		final long date = c.getLong(CallLogQuery.DATE);

		TextView name_textview = (TextView) view
				.findViewById(R.id.call_log_name);
		CallTypeIconsView callTypeIconsView = (CallTypeIconsView) view
				.findViewById(R.id.call_log_type_icons);
		TextView date_textview = (TextView) view
				.findViewById(R.id.call_log_location_and_date);
		ImageView play_record = (ImageView) view
				.findViewById(R.id.call_log_paly_record);

		if (TextUtils.isEmpty(name)) {
			name_textview.setText(number);
		} else {
			name_textview.setText(name);
		}

		final int[] callTypes = getCallTypes(c, count);
		callTypeIconsView.clear();
		int count1 = callTypes.length;
		for (int index = 0; index < count1 && index < MAX_CALL_TYPE_ICONS; ++index) {
			callTypeIconsView.add(callTypes[index]);
		}
		callTypeIconsView.requestLayout();
		callTypeIconsView.setVisibility(View.VISIBLE);

		final Integer callCount;
		if (count > MAX_CALL_TYPE_ICONS) {
			callCount = count;
		} else {
			callCount = null;
		}
		CharSequence dateText = getCallDate(date);
		setCallCountAndDate(date_textview, callCount, dateText);

		setPlayRecordView(play_record, callTypes, number);
	}

	private void setPlayRecordView(ImageView play_record,
			final int[] callTypes, final String number) {
		boolean isShowPlay = false;
		if (callTypes != null) {
			for (int i = 0; i < callTypes.length; i++) {
				if (callTypes[i] == Calls.MISSED_TYPE) {
					isShowPlay = true;
					break;
				}
			}
		}
		if (isShowPlay) {
			play_record.setVisibility(View.VISIBLE);
			play_record.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					//test
					String path = Environment.getExternalStorageDirectory().getAbsolutePath();
					path += "/ione.wav";
					player.setRecorderPath(path);
					//test
					showVoiceProgressDialog();
					player.startPlayback(player.playProgress());
				}
			});
		} else {
			play_record.setVisibility(View.GONE);
		}
	}

	private void setCallCountAndDate(TextView views, Integer callCount,
			CharSequence dateText) {
		// Combine the count (if present) and the date.
		final CharSequence text;
		if (callCount != null) {
			text = mContext.getResources().getString(
					R.string.call_log_item_count_and_date,
					callCount.intValue(), dateText);
		} else {
			text = dateText;
		}

		views.setText(text);
	}

	private int[] getCallTypes(Cursor cursor, int count) {
		int position = cursor.getPosition();
		int[] callTypes = new int[count];
		for (int index = 0; index < count; ++index) {
			callTypes[index] = cursor.getInt(CallLogQuery.CALL_TYPE);
			cursor.moveToNext();
		}
		cursor.moveToPosition(position);
		return callTypes;
	}

	private CharSequence getCallDate(long date) {
		return DateUtils.getRelativeTimeSpanString(date,
				System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS,
				DateUtils.FORMAT_ABBREV_RELATIVE);
	}

	private CustomProgressBar mProgressBar;
	private TextView mVoiceTextView;
	private String mTimerFormat;
	private AlertDialog alertDialog;
	private final Handler mHandler = new Handler();
	private Runnable mUpdateSeekBar = new Runnable() {
		@Override
		public void run() {
			updateProgress();
		}
	};

	private Runnable mUpdateTimer = new Runnable() {
		public void run() {
			updateTimerView();
		}
	};

	private void updateProgress() {
		mProgressBar.setProgress((int) (360 * player.playProgress()));
		mHandler.postDelayed(mUpdateSeekBar, 10);
	}

	private void updateTimerView() {
		int state = player.state();

		boolean ongoing = state == Recorder.RECORDING_STATE
				|| state == Recorder.PLAYING_STATE;

		long time = player.progress();
		String timeStr = String.format(mTimerFormat, time / 60, time % 60);
		mVoiceTextView.setText(timeStr);

		if (ongoing) {
			mHandler.postDelayed(mUpdateTimer, 500);
		}
	}

	protected void showVoiceProgressDialog() {
		mTimerFormat = mContext.getResources().getString(R.string.timer_format);
		AlertDialog.Builder builder = new Builder(mContext);// R.style.WatchDialogTheme
		View view = mContext.getLayoutInflater().inflate(
				R.layout.voice_play_dialog_view, null);
		mProgressBar = (CustomProgressBar) (view
				.findViewById(R.id.stateProgressBar));
		mVoiceTextView = (TextView) (view.findViewById(R.id.voice_second_view));
		Button close_btn = (Button) (view.findViewById(R.id.close_btn));
		final ImageView play_btn = (ImageView) (view
				.findViewById(R.id.start_stop_img));
		builder.setView(view);
		alertDialog = builder.create();
		close_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				player.stop();
				alertDialog.dismiss();
			}
		});
		play_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (player.state() == Recorder.PLAYING_STATE) {
					play_btn.setImageResource(R.drawable.ic_vm_play_dk);
					player.pausePlayback();
				} else if (player.state() == Recorder.PLAYING_PAUSED_STATE) {
					play_btn.setImageResource(R.drawable.ic_vm_pause_dk);
					player.startPlayback(player.playProgress());
				}
			}
		});
		alertDialog.show();
	}

	@Override
	public void onStateChanged(int state) {
		if (player.state() == Recorder.PLAYING_STATE) {
			updateProgress();
			updateTimerView();
		} else if (player.state() == Recorder.IDLE_STATE) {
			if (alertDialog.isShowing()) {
				alertDialog.dismiss();
			}
		}
	}

	@Override
	public void onError(int error) {

	}
	
	@Override
	protected void addGroups(Cursor cursor) {
		mCallLogGroupBuilder.addGroups(cursor);
	}

	@Override
	public void addGroup(int cursorPosition, int size, boolean expanded) {
		super.addGroup(cursorPosition, size, expanded);
	}

	@Override
	public void setDayGroup(long rowId, int dayGroup) {
	}

	@Override
	public void clearDayGroups() {
	}

	@Override
	protected void bindChildView(View view, Context arg1, Cursor cursor) {
		bindView(view, cursor, 1);
	}

	@Override
	protected void bindGroupView(View view, Context arg1, Cursor cursor,
			int groupSize, boolean arg4) {
		bindView(view, cursor, groupSize);
	}

	@Override
	protected void bindStandAloneView(View view, Context arg1, Cursor cursor) {
		bindView(view, cursor, 1);
	}

	@Override
	protected View newChildView(Context arg0, ViewGroup parent) {
		return mInflater.inflate(R.layout.call_log_list_view, parent, false);
	}

	@Override
	protected View newGroupView(Context context, ViewGroup parent) {
		return newChildView(context, parent);
	}

	@Override
	protected View newStandAloneView(Context context, ViewGroup parent) {
		return newChildView(context, parent);
	}
}
